package com.xds.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.xds.common.exception.NoStockException;
import com.xds.common.to.OrderTo;
import com.xds.common.utils.R;
import com.xds.common.vo.MemberResVo;
import com.xds.gulimall.order.constant.OrderConstant;
import com.xds.gulimall.order.controller.OrderReturnReasonController;
import com.xds.gulimall.order.entity.OrderItemEntity;
import com.xds.gulimall.order.enume.OrderStatusEnum;
import com.xds.gulimall.order.feign.*;
import com.xds.gulimall.order.interceptor.LoginUserInterceptor;
import com.xds.gulimall.order.service.OrderItemService;
import com.xds.gulimall.order.to.OrderCreateTo;
import com.xds.gulimall.order.vo.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xds.common.utils.PageUtils;
import com.xds.common.utils.Query;
import com.xds.gulimall.order.dao.OrderDao;
import com.xds.gulimall.order.entity.OrderEntity;
import com.xds.gulimall.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {
    @Autowired
    MemberFeign memberFeign;
    @Autowired
    Cartfeign cartfeign;
    @Autowired
    ThreadPoolExecutor executor;
    @Autowired
    WareFeign wareFeign;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    ProductFeign productFeign;
    @Autowired
    OrderItemService orderItemService;
    @Autowired
    RabbitTemplate rabbitTemplate;

    private ThreadLocal<OrderSubmitVo> confirmVoThreadLocal=new ThreadLocal<>();
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 订单确认页需要返回的数据
     * @return
     */
    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVo confirmVo = new OrderConfirmVo();
        MemberResVo memberResVo = LoginUserInterceptor.loginUser.get();
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        CompletableFuture<Void> AddressFuture = CompletableFuture.runAsync(() -> {
            //1.远程查询所有收货地址列表
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<OrderConfirmVo.MemberAddressVo> address = memberFeign.getAddress(memberResVo.getId());
            confirmVo.setAddress(address);
        }, executor);
        CompletableFuture<Void> CartItemFuture = CompletableFuture.runAsync(() -> {
            //2.远程查询购物车所有选中的购物项
            //feign远程调用会丢失请求头
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<OrderConfirmVo.OderItemVo> items = cartfeign.getCurrentItems();
            confirmVo.setItems(items);
        }, executor).thenRunAsync(()->{
            List<OrderConfirmVo.OderItemVo> items = confirmVo.getItems();
            List<Long> collect = items.stream().map(item -> item.getSkuId()).collect(Collectors.toList());
            R hasStocke = wareFeign.getSkusHasStocke(collect);
            List<SkuStockVo> data = hasStocke.getData(new TypeReference<List<SkuStockVo>>() {
            });
            if (data!=null){
                Map<Long, Boolean> map = data.stream().collect(Collectors.toMap(SkuStockVo::getSkuId, SkuStockVo::getHasStock));
                confirmVo.setStocks(map);
            }
        },executor);

        //3.查询用户积分
        confirmVo.setIntegration( memberResVo.getIntegration());
        //4.其他数据自动计算
        //5.防重令牌
        //TODO 防重令牌
        String token = UUID.randomUUID().toString().replace("-", "");
        confirmVo.setOrderToken(token);
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX+memberResVo.getId(),token,30, TimeUnit.MINUTES);
        CompletableFuture.allOf(AddressFuture,CartItemFuture).get();
        return confirmVo;

    }

    /**
     * 下单操作
     * @param vo
     * @return
     */
    @Transactional
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo vo) {
        SubmitOrderResponseVo responseVo=new SubmitOrderResponseVo();
        MemberResVo memberResVo = LoginUserInterceptor.loginUser.get();
        responseVo.setCode(0);
        confirmVoThreadLocal.set(vo);
        //1.验证令牌
        String orderToken = vo.getOrderToken();
//        String redisToken = redisTemplate.opsForValue().get(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberResVo.getId());
         //令牌删除原子性 脚本
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
//        if (orderToken!=null&&orderToken.equals(redisToken)){
//            //令牌验证通过
//            //删除令牌 验证和删除必须保证原子性
//            redisTemplate.delete(OrderConstant.USER_ORDER_TOKEN_PREFIX+memberResVo.getId());
//        }else {
//            //令牌验证不通过
//
//        }
        //原子验证令牌和删除令牌
        Long result = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class),
                Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberResVo.getId()), orderToken);
        if (result==0){
            //令牌验证失败
            responseVo.setCode(1);
            return responseVo;
        }else {
            //令牌验证成功
              //下单创建订单
            OrderCreateTo order = createOrder();
            //验价
            BigDecimal payAmount = order.getOrder().getPayAmount();
            BigDecimal payPrice = vo.getPayPrice();
          if (Math.abs( payAmount.subtract(payAmount).doubleValue())<0.01){
              //金额对比成功
               //保存订单
              saveOrder(order);
              //4、库存锁定,只要有异常，回滚订单数据
              WareSkuLockVo lockVo = new WareSkuLockVo();
              lockVo.setOrderSn(order.getOrder().getOrderSn());

              //获取出要锁定的商品数据信息
              List<OrderConfirmVo.OderItemVo> orderItemVos = order.getItems().stream().map((item) -> {
                  OrderConfirmVo.OderItemVo orderItemVo = new OrderConfirmVo.OderItemVo();
                  orderItemVo.setSkuId(item.getSkuId());
                  orderItemVo.setCount(item.getSkuQuantity());
                  orderItemVo.setTitle(item.getSkuName());
                  return orderItemVo;
              }).collect(Collectors.toList());
              lockVo.setLocks(orderItemVos);
              //TODO 调用远程锁定库存的方法
              //出现的问题：扣减库存成功了，但是由于网络原因超时，出现异常，导致订单事务回滚，库存事务不回滚(解决方案：seata)
              //为了保证高并发，不推荐使用seata，因为是加锁，并行化，提升不了效率,可以发消息给库存服务
              R r = wareFeign.orderLockStock(lockVo);
              if (r.getCode() == 0) {
                  //锁定成功
                  responseVo.setOrder(order.getOrder());
                  //模拟远程扣积分异常
//                   int i = 10/0;

                  //TODO 订单创建成功，发送消息给MQ
                  rabbitTemplate.convertAndSend("order-event-exchange","order.create.order",order.getOrder());

                  //删除购物车里的数据
//                  redisTemplate.delete(OrderConstant.USER_ORDER_TOKEN_PREFIX+memberResVo.getId());
                  return responseVo;
              } else {
                  //锁定失败
                  String msg = (String) r.get("msg");
                  throw new NoStockException(msg);
//                   responseVo.setCode(3);
//                   return responseVo;
              }
          }else {
              responseVo.setCode(2);
              return responseVo;
          }
        }
//        return responseVo;

    }

    /**
     * 订单超时未支付 关闭
     * @param entity
     */
    @Override
    public void closeOrder(OrderEntity entity) {
        //查询当前订单的最新状态
        OrderEntity orderEntity = this.getById(entity.getId());
        System.out.println(orderEntity.getStatus());
        if (orderEntity.getStatus()==OrderStatusEnum.CREATE_NEW.getCode()){
            //关单
            orderEntity.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(orderEntity);
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(orderEntity,orderTo);
            try {
                //TODO 保证消息一定会发出去 每一个消息做好日志记录。
                rabbitTemplate.convertAndSend("order-event-exchange","order.release.other",orderTo);
            }catch (Exception e){
                //TODO 将没发送成功的消息进行重新发送

            }
        }
    }

    /**
     * 保存订单数据
     * @param orderCreateTo
     */
    private void saveOrder(OrderCreateTo orderCreateTo) {
        //获取订单信息
        OrderEntity order = orderCreateTo.getOrder();
        order.setModifyTime(new Date());
        order.setCreateTime(new Date());
        //保存订单
        this.baseMapper.insert(order);

        //获取订单项信息
        List<OrderItemEntity> orderItems = orderCreateTo.getItems();
        //批量保存订单项数据
        orderItemService.saveBatch(orderItems);
    }

    private OrderCreateTo createOrder(){
        OrderCreateTo createTo=new OrderCreateTo();
        //1.生成订单号
        String orderSn = IdWorker.getTimeId();
        OrderEntity orderEntity = buildOrder(orderSn);
        //2.获取到所有的订单项
        List<OrderItemEntity> items = buildOrderItems(orderSn);
        //3.验价
        computerPrice(orderEntity,items);
        createTo.setOrder(orderEntity);
        createTo.setItems(items);
        return createTo;
    }

    private void computerPrice(OrderEntity orderEntity, List<OrderItemEntity> items) {

        //总价
        BigDecimal total = new BigDecimal("0.0");
        //优惠价
        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal intergration = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");

        //积分、成长值
        Integer integrationTotal = 0;
        Integer growthTotal = 0;

        //订单总额，叠加每一个订单项的总额信息
        for (OrderItemEntity orderItem : items) {
            //优惠价格信息
            coupon = coupon.add(orderItem.getCouponAmount());
            promotion = promotion.add(orderItem.getPromotionAmount());
            intergration = intergration.add(orderItem.getIntegrationAmount());

            //总价
            total = total.add(orderItem.getRealAmount());

            //积分信息和成长值信息
            integrationTotal += orderItem.getGiftIntegration();
            growthTotal += orderItem.getGiftGrowth();

        }
        //1、订单价格相关的
        orderEntity.setTotalAmount(total);
        //设置应付总额(总额+运费)
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        orderEntity.setCouponAmount(coupon);
        orderEntity.setPromotionAmount(promotion);
        orderEntity.setIntegrationAmount(intergration);

        //设置积分成长值信息
        orderEntity.setIntegration(integrationTotal);
        orderEntity.setGrowth(growthTotal);

        //设置删除状态(0-未删除，1-已删除)
        orderEntity.setDeleteStatus(0);

    }

    /**
     * 构建订单
     * @param orderSn
     */
    private OrderEntity buildOrder(String orderSn) {
        MemberResVo memberResVo = LoginUserInterceptor.loginUser.get();
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(orderSn);
        orderEntity.setMemberId(memberResVo.getId());
        //获取收货地址信息
        OrderSubmitVo submitVo = confirmVoThreadLocal.get();
        R fare = wareFeign.getFare(submitVo.getAddrId());
        FareVo fareResp = fare.getData(new TypeReference<FareVo>() {
        });
        //运费金额
        orderEntity.setFreightAmount(fareResp.getFare());
        //收货人的地址
        orderEntity.setReceiverDetailAddress(fareResp.getAddressVo().getDetailAddress());
        //收货人的姓名
        orderEntity.setReceiverName(fareResp.getAddressVo().getName());
        //收货人的手机号
        orderEntity.setReceiverPhone(fareResp.getAddressVo().getPhone());
        //收货人的邮编
        orderEntity.setReceiverPostCode(fareResp.getAddressVo().getPostCode());
        //收货人的省
        orderEntity.setReceiverProvince(fareResp.getAddressVo().getProvince());
        return orderEntity;
    }

    /**
     * 构建所有订单项
     * @param
     * @return
     */
    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        //最后确定每个购物项的价格
        List<OrderConfirmVo.OderItemVo> currentItems = cartfeign.getCurrentItems();
        if (currentItems!=null&&currentItems.size()>0){
            List<OrderItemEntity> itemEntities = currentItems.stream().map(cartItem -> {
                OrderItemEntity itemEntity =  buildOrderItem(cartItem);
                itemEntity.setOrderSn(orderSn);
                return itemEntity;
            }).collect(Collectors.toList());
            return itemEntities;
        }

        return null;
    }

    /**
     * 构建每一个订单项
     * @param cartItem
     * @return
     */
    private OrderItemEntity buildOrderItem(OrderConfirmVo.OderItemVo cartItem) {
        OrderItemEntity orderItemEntity=new OrderItemEntity();
        //1订单信息 订单号
        //2.商品的spu信息
        Long skuId = cartItem.getSkuId();
        R r = productFeign.getSpuInfoBySkuId(skuId);
        SpuInfoVo data = r.getData(new TypeReference<SpuInfoVo>() {
        });
        orderItemEntity.setSpuId(data.getId());
        orderItemEntity.setSpuBrand(data.getBrandId().toString());
        orderItemEntity.setSpuName(data.getSpuName());
        orderItemEntity.setCategoryId(data.getCatalogId());
        //3.商品的sku信息
        orderItemEntity.setSkuId(cartItem.getSkuId());
        orderItemEntity.setSkuName(cartItem.getTitle());
        orderItemEntity.setSkuPic(cartItem.getImage());
        orderItemEntity.setSkuPrice(cartItem.getPrice());
        String skuAttr = StringUtils.collectionToDelimitedString(cartItem.getSkuAttrValues(), ";");
        orderItemEntity.setSkuAttrsVals(skuAttr);
        orderItemEntity.setSkuQuantity(cartItem.getCount());
        //4.优惠信息 忽略
        //5.积分信息
        orderItemEntity.setGiftGrowth(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount())).intValue());
        orderItemEntity.setGiftIntegration(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount())).intValue());
        //6.订单项的价格信息
        orderItemEntity.setPromotionAmount(new BigDecimal("0.0"));
        orderItemEntity.setCouponAmount(new BigDecimal("0.0"));
        orderItemEntity.setIntegrationAmount(new BigDecimal("0.0"));
//        BigDecimal orign = new BigDecimal(orderItemEntity.getSkuPic()).multiply(new BigDecimal(orderItemEntity.getSkuQuantity().toString()));
        BigDecimal origin = orderItemEntity.getSkuPrice().multiply(new BigDecimal(orderItemEntity.getSkuQuantity().toString()));
//        BigDecimal subtract = origin.subtract(orderItemEntity.getCouponAmount()).subtract(orderItemEntity.getPromotionAmount()).
//                subtract(orderItemEntity.getIntegrationAmount());
//        orderItemEntity.setRealAmount(subtract);
        BigDecimal subtract = origin.subtract(orderItemEntity.getCouponAmount())
                .subtract(orderItemEntity.getPromotionAmount())
                .subtract(orderItemEntity.getIntegrationAmount());
        orderItemEntity.setRealAmount(subtract);
        return orderItemEntity;
    }

}